package cn.jiyun.redis.service.impl;

import cn.jiyun.redis.dao.EmpDao;
import cn.jiyun.redis.pojo.Emp;
import cn.jiyun.redis.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpDao empDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public List<Emp> findAll() {
        /*String[] name={"欣欣","丽丽","咳咳","卡卡","方法","三十","天天","哦哦","匹配","九价"};
        for (int i = 0; i < name.length; i++) {
            redisTemplate.opsForZSet().add("redis",name[i],0);
        }*/

        ArrayList<Emp> arrayList = new ArrayList<>();
        Set<Object> redis = redisTemplate.opsForZSet().reverseRange("redis", 0, -1);
        for (Object redi : redis) {
            Double score = redisTemplate.opsForZSet().score("redis", redi);
            Emp emp = new Emp();
            emp.setNum(score);
            emp.setName(redi.toString());
            arrayList.add(emp);
        }
        log.info("arrayList:{}",arrayList);
        return arrayList;
    }

    @Override
    public void dian(String name) throws UnknownHostException {
        //1.redis的 String类型 key=ip value次数 并设置过期时间24hours
        String ip = Inet4Address.getLocalHost().getHostAddress();
        //查询
        String i = (String) redisTemplate.opsForValue().get(ip);
        if(i!=null){
            //点过了
            Integer cs = Integer.valueOf(i);
            //点没过10次
            if(cs<10){
                cs++;
                redisTemplate.opsForValue().set(ip,cs+"",0);
            }else {
                System.out.println("超过限制了！明天再来！！！");
                return;
            }
        }else {
            //没点过 帮他点一下
            redisTemplate.opsForValue().set(ip,"1",1, TimeUnit.DAYS);
        }
        redisTemplate.opsForZSet().incrementScore("redis",name,1);
    }
}
